package cs2340.quarterblack.wheresmystuff;

//import java.util.HashMap;
//
//
//import java.sql.Connection;
//import java.sql.DriverManager;
//import java.sql.ResultSet;
//import java.sql.SQLException;
//import java.sql.Statement;
//import javax.naming.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.List;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONObject;

import cs2340.quarterblack.wheresmystuff.Database.DBDataCapsule;
import android.os.AsyncTask;
import android.util.Log;

public class DatabaseTask extends AsyncTask<DBDataCapsule,Void,String>{

        static InputStream is = null;
        static JSONObject jObj = null;
        static String response = "";
        static String url = "http://eggames.mooo.com:10424/";
        List<NameValuePair> params = new ArrayList<NameValuePair>();

        // function get json from url
        // by making HTTP POST or GET mehtod
        
        @Override
        protected String doInBackground(DBDataCapsule... arg0) {
                switch (arg0[0].getAction()){
                case CHECK_LOGIN:
            		url = url + "check_login";
            		break;
                case ADD_ACCOUNT:
                	url = url + "add_user";
                	break;
                case LOCK_ACCOUNT:
                	url = url + "change_user_status";
                	break;
                case UNLOCK_ACCOUNT:
                	url = url + "change_user_status";
                	break;
                case ADD_ITEM:
            		url = url + "add_item";
            		break;
                case SET_PRIVILEDGES:
                	url = url + "change_user_privileges";
                	break;
                case DELETE_ITEM:
                	url = url + "remove_item";
                	break;
                case DELETE_ACCOUNT:
                	url = url + "remove_user";
                	break;
                case GET_USERS_ITEMS:
                	url = url + "get_user_items";
                	break;
                case GET_ACCOUNTS:
                	url = url + "get_user";
                	break;
                case CHECK_EXISTS:
                	url = url + "check_user_existance";
                	break;
                case GET_ALL_ITEMS:
                	url = url + "get_all_items";
                	break;
                };
        		params = arg0[0].getParameters();
                // Making HTTP request
                try {

                        // check for request method
                        //                  if(method == "POST"){
                        // request method is POST
                        // defaultHttpClient
                        DefaultHttpClient httpClient = new DefaultHttpClient(); 
                        HttpPost httpPost = new HttpPost(url);
                        httpPost.setEntity(new UrlEncodedFormEntity(params));

                        HttpResponse httpResponse = httpClient.execute(httpPost);
                        HttpEntity httpEntity = httpResponse.getEntity();
                        is = httpEntity.getContent();

                        //                  }else if(method == "GET"){
                        //                      // request method is GET
                        //                      DefaultHttpClient httpClient = new DefaultHttpClient();
                        //                      String paramString = URLEncodedUtils.format(params, "utf-8");
                        //                      url += "?" + paramString;
                        //                      HttpGet httpGet = new HttpGet(url);
                        //       
                        //                      HttpResponse httpResponse = httpClient.execute(httpGet);
                        //                      HttpEntity httpEntity = httpResponse.getEntity();
                        //                      is = httpEntity.getContent();
                        //                  }           

                } catch (UnsupportedEncodingException e) {
                        e.printStackTrace();
                } catch (ClientProtocolException e) {
                        e.printStackTrace();
                } catch (IOException e) {
                        e.printStackTrace();
                }
                String json = "";
                try {
                        BufferedReader reader = new BufferedReader(new InputStreamReader(
                                        is, "iso-8859-1"), 8);
                        StringBuilder sb = new StringBuilder();
                        String line = null;
                        while ((line = reader.readLine()) != null) {
                                sb.append(line + "\n");
                        }
                        is.close();
                        json = sb.toString();
                } catch (Exception e) {
                        Log.e("Buffer Error", "Error converting result " + e.toString());
                }
                return json; 

        }
//      public static void main(String[] args) {
//              Account test = new Account("jonny", "man");
//              test.checkLogin();
//      }
        
}
        
        
        
        
        
        
        
        
        
        
        
        
        
//      static HashMap<String, String> database = new HashMap<String, String>();
//      static Connection conn=null;
//      static Statement stmt;
//      
//      public int hashPw(String pw){
//              int hash = pw.hashCode();
//              return hash;
//      }
//      
//      /**
//       * This method is to add an account to the database
//       * @param acc The account object to be added to the database
//       * @return the string "sql exception" if the addition failed, or "Done" if it was a success
//       */
//      public static String add(Account newUser){
//              //open connection
//               try {
//                      Class.forName("com.mysql.jdbc.Driver");
//                  } catch (ClassNotFoundException e) {
//                      // TODO Auto-generated catch block
//                      e.printStackTrace();
//                  }           
//              
//              
//              try {
//                                      conn = DriverManager.getConnection("jdbc:mysql://128.61.104.124:10425/Wheres_my_stuff", "App_user", "^L@qL8JFyl#CaSwm!Ykd*PV7i$8^3g");
//                                      stmt = conn.createStatement();
//                              } 
//                              catch(SQLException se){
//                                      se.printStackTrace();
//                                      System.out.println(se.getMessage() + "1");
//                              }
//                              
//                              int rowCount;
//                              try {
//                                      String pw = newUser.getPw();
//                                      String userId = newUser.getUserId();
//                                      String type = newUser.getType();
//                                      String email = newUser.getEmail();
//                                      boolean status = false;
//                                      //insert query
//                                      rowCount = stmt.executeUpdate("insert into accounts (userID, password, type, email, status) values ('"+userId+"', '"+pw+"', '"+type+"', '"+email+"', "+status+");");
//                                      //close connection---------
//                                      try {
//                                              conn.close();
//                                      } catch (SQLException se) {
//                                              se.printStackTrace();
//                                              System.out.println(se.getMessage() + "2");
//                                      }
//                                      //-------------------------
//                                      return "Done";
//                              } catch (SQLException e) {
//                                      e.printStackTrace();
//                                      return "sql exception";
//                              }
//                      }
//      
//      /**
//       * The method checks the login attempt of an account and returns whether the name
//       * and password match
//       * @param acc the account object to be used
//       * @return "not a match" if the password doesn't match the userID or the query failed. The userID otherwise.
//       */
//      public static String checkLogin(Account newUser) {
//              //open connection
//              try {
//                      Class.forName("com.mysql.jdbc.Driver").newInstance();
//              } catch (ClassNotFoundException e) {
//                      // TODO Auto-generated catch block
//                      e.printStackTrace();
//              } catch (InstantiationException e) {
//                      // TODO Auto-generated catch block
//                      e.printStackTrace();
//              } catch (IllegalAccessException e) {
//                      // TODO Auto-generated catch block
//                      e.printStackTrace();
//              } 
//
//              try {
//                      conn = DriverManager.getConnection("jdbc:mysql://128.61.104.124:10425/Wheres_my_stuff", "App_user", "^L@qL8JFyl#CaSwm!Ykd*PV7i$8^3g");
//                      stmt = conn.createStatement();
//              } 
//              catch(SQLException se){
//                      System.out.println(se.getMessage());
//              }
//
//              //query
//              ResultSet rs;
//              try {
//                      String pw = newUser.getPw();
//                      String userId = newUser.getUserId();
//                      rs = stmt.executeQuery("select userID from accounts where userID='"+userId+"' AND password='"+pw+"';");
//                      } catch (SQLException e) {
//                              e.printStackTrace();
//                              return "exception";
//                      }
//                      
//                      //-------------------------
//                      try {
//                              if(rs.next()){
//                                      try {
//                                              return rs.getString("userID");
//                                      } catch (SQLException e) {
//                                              // TODO Auto-generated catch block
//                                              e.printStackTrace();
//                                      }
//                              }else{
//                                      return "not a match";
//                              }
//                      } catch (SQLException e) {
//                              // TODO Auto-generated catch block
//                              e.printStackTrace();
//                      }
//                      //close connection---------
//                      try {
//                              
//                              rs.close();
//                              stmt.close();
//                              conn.close();
//                      } catch (SQLException se) {
//                              se.printStackTrace();
//                              System.out.println(se.getMessage());
//                      }
//              return "something failed";
//      } 
//}
//      private static void initializedb() {
//              if (database.isEmpty()) {
//              database.put("bob", "password");
//              database.put("troll", "trololol");
//              database.put("man", "dude");
//              database.put("jim", "woo");
//              database.put("bomber", "man");
//              }
//      }
//      public static String add(Account newUser){
//              initializedb();
//              database.put(newUser.getUserId(), newUser.getPw());
//              return "done";
//      }
//      private static boolean checkExists(Account user)
//      {
//              if(database.containsKey(user.getUserId()) == true)
//              {
//                      return true;
//              }
//              else
//              {
//                      return false;
//              }
//      }
//      public static String checkLogin(Account newUser) {
//              initializedb();
//              String dbPassword = database.get(newUser.getUserId());
//              if (newUser.getPw().equals(dbPassword)) {
//                      return newUser.getUserId();
//              }
//              else {
//                      return "nope";
//              }
//      }

        
//}
